package cn.zmit.kuxi.activity;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Random;

import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import cn.zmit.kuxi.R;
import cn.zmit.kuxi.alipay.PayResult;
import cn.zmit.kuxi.alipay.SignUtils;
import cn.zmit.kuxi.contants.SPConstants;
import cn.zmit.kuxi.contants.Url;
import cn.zmit.kuxi.image.ImageDisplayer;

import com.alipay.sdk.app.PayTask;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.xdroid.common.utils.PreferenceHelper;

public class RechargeActivity extends BaseActivity {
	@ViewInject(R.id.bt_commit)
	private Button bt_commit;
	@ViewInject(R.id.img_shiyuan)
	private ImageView img_shiyuan;
	@ViewInject(R.id.img_sanshi)
	private ImageView img_sanshi;
	@ViewInject(R.id.img_wushi)
	private ImageView img_wushi;
	@ViewInject(R.id.img_yibai)
	private ImageView img_yibai;
	@ViewInject(R.id.img_pay)
	private ImageView img_pay;
	@ViewInject(R.id.rl_shiyuan)
	private RelativeLayout rl_shiyuan;
	@ViewInject(R.id.rl_sanshi)
	private RelativeLayout rl_sanshi;
	@ViewInject(R.id.rl_wushi)
	private RelativeLayout rl_wushi;
	@ViewInject(R.id.rl_yibai)
	private RelativeLayout rl_yibai;
	@ViewInject(R.id.rl_pay)
	private RelativeLayout rl_pay;
	@ViewInject(R.id.tv_my_user_name)
	private TextView tv_my_user_name;
	@ViewInject(R.id.tv_kubi_money)
	private TextView tv_kubi_money;
	@ViewInject(R.id.tv_my_user_phone_num)
	private TextView tv_my_user_phone_num;
	@ViewInject(R.id.edit_inputMoney)
	private EditText edit_inputMoney;
	@ViewInject(R.id.imag_user_pic)
	private ImageView imag_user_pic;
	String pic, name, kubi, phone;

	public String amount;
	private int old_amount;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setTitleView("充值记录", true);
		setContentView(R.layout.activity_recharge);
		ViewUtils.inject(this);
		initView();
		userid = PreferenceHelper.readString(context,
				SPConstants.SHARED_PREFERENCE_NAME, SPConstants.USERID, "");
		et_inputmoney = (EditText) findViewById(R.id.edit_inputMoney);

		// et_inputmoeny listener
		et_inputmoney.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				et_inputmoney.setFocusable(true);
				et_inputmoney.setFocusableInTouchMode(true);
				et_inputmoney.requestFocus();
				img_shiyuan.setVisibility(View.GONE);
				img_sanshi.setVisibility(View.GONE);
				img_wushi.setVisibility(View.GONE);
				img_yibai.setVisibility(View.GONE);
				amount = 0 + "";
			}
		});
	}

	Boolean hasLog;

	private void initView() {
		pic = getTextFromBundle("pic");
		name = getTextFromBundle("name");
		kubi = getTextFromBundle("kubi");
		old_amount = Integer.parseInt(kubi);
		phone = getTextFromBundle("phone");
		if (pic != null && pic.length() > 0) {
			ImageDisplayer.getInstance().dispalyImageWithRadius(
					Url.IMAGR_ROOT + pic, imag_user_pic, 0);
		} else {
			imag_user_pic.setImageResource(R.drawable.user_pic_def);
		}
		tv_my_user_name.setText("昵称：" + name);
		tv_kubi_money.setText("酷币：" + kubi);
		tv_my_user_phone_num.setText("手机号：" + phone);

	}

	@OnClick({ R.id.bt_commit, R.id.rl_shiyuan, R.id.rl_sanshi, R.id.rl_wushi,
			R.id.rl_yibai })
	private void OnClick(View v) {
		switch (v.getId()) {
		case R.id.bt_commit:
			String et_amount = et_inputmoney.getText().toString();
			if (!et_amount.equals("")) {
				amount = et_amount;
				AsyncHttpClient ahc = new AsyncHttpClient();
				RequestParams params = new RequestParams();
				params.add("user_id", userid);
				params.add("amount", amount);
				ahc.post(Url.RECHARGE, params, new MyResponseHandler());

			} else {// 只要et_amount为空，如果同时也没勾选，为提示非法操作
				AsyncHttpClient ahc = new AsyncHttpClient();
				RequestParams params = new RequestParams();
				params.add("user_id", userid);
				params.add("amount", amount);
				ahc.post(Url.RECHARGE, params, new MyResponseHandler());
			}

			break;
		case R.id.rl_shiyuan:
			amount = 10 + "";
			img_shiyuan.setVisibility(View.VISIBLE);
			img_sanshi.setVisibility(View.GONE);
			img_wushi.setVisibility(View.GONE);
			img_yibai.setVisibility(View.GONE);
			et_inputmoney.setText("");
			et_inputmoney.setFocusable(false);
			break;
		case R.id.rl_sanshi:
			amount = 30 + "";
			img_sanshi.setVisibility(View.VISIBLE);
			img_shiyuan.setVisibility(View.GONE);
			img_wushi.setVisibility(View.GONE);
			img_yibai.setVisibility(View.GONE);
			et_inputmoney.setText("");
			et_inputmoney.setFocusable(false);
			break;
		case R.id.rl_wushi:
			amount = 50 + "";
			img_wushi.setVisibility(View.VISIBLE);
			img_sanshi.setVisibility(View.GONE);
			img_shiyuan.setVisibility(View.GONE);
			img_yibai.setVisibility(View.GONE);
			et_inputmoney.setText("");
			et_inputmoney.setFocusable(false);
			break;
		case R.id.rl_yibai:
			amount = 100 + "";
			img_yibai.setVisibility(View.VISIBLE);
			img_sanshi.setVisibility(View.GONE);
			img_wushi.setVisibility(View.GONE);
			img_shiyuan.setVisibility(View.GONE);
			et_inputmoney.setText("");
			et_inputmoney.setFocusable(false);
			break;
		default:
			break;
		}
	}

	class MyResponseHandler extends AsyncHttpResponseHandler {

		@Override
		public void onFailure(int arg0, Header[] arg1, byte[] arg2,
				Throwable arg3) {
			Toast.makeText(context, "网络错误", 0).show();
		}

		@Override
		public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
			String response = new String(arg2);
			try {
				JSONObject obj = new JSONObject(response);
				code = obj.getString("code");
				order_no = obj.getString("order_no");
				amount_back = obj.getString("amount");
			} catch (JSONException e) {
				e.printStackTrace();
			}
			if (code.equals("1")) {
				Toast.makeText(context, "生成订单成功，去付款！", 0).show();
				if (isInstalled(context)) {
					pay(amount_back, order_no);
				} else {
					Toast.makeText(context, "请先安装支付宝", 0).show();
				}

			}
			if (code.equals("0")) {
				Toast.makeText(context, "非法操作", 0).show();
			}
		}
	}

	// com.eg.android.AlipayGphone

	// check intalled app
	public Boolean isInstalled(Context context) {
		PackageManager pm = getPackageManager();
		List<PackageInfo> infos = pm.getInstalledPackages(0);
		for (PackageInfo info : infos) {
			if (info.packageName.equals("com.eg.android.AlipayGphone")) {
				return true;
			}
		}
		return false;
	}

	// server back info
	private String code;
	private String order_no;
	private String amount_back;
	private EditText et_inputmoney;

	/**
	 * 
	 * 暂时仅考虑支付宝支付
	 * 
	 * @author Joash_Yan
	 */

	// 支付宝支付功能

	// 复制到支付的页面，购物车点击提交的页面

	// 商户PID
	public static final String PARTNER = "2088611733777860";
	// 商户收款账号
	public static final String SELLER = "18655386599@163.com";
	// 商户私钥，pkcs8格式

	public static final String RSA_PRIVATE = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAORKbnGihXbb6eneu7mw7O82T46dgpwUqJtMZeppp7lQJK93UALMokKKLO7VeeC+C5UpHtd8pNMzM+LCw8Bs7rCH+JaQLGsTgY/l +TZEPv6eZoifhcbeyA5VZhF4pblYTAJfd8GgKkFiqSC6QeAAwA5gYQLXuwQZjDmEy6e7r6mBAgMBAAECgYA/dr2rU3384/fsLyJK5feILLYDNKB5mXih66QtfX/GEZSRPv78OD0neFgzcR83rj10EwFi8GC14fcbo/9dQCs +W57SYJVtrZLjCv7BQEYW66LVhSHyJ66IQnkQdh3ejqew4N3CwQ2CgJDsFJRNPg +ceP91Tev9+b7t06xqTrRQbQJBAPqQnoXDJsyLGPd0vBe2tENx7RmcWRJ2TKPz4DCXeFBGjGNc8tl9yklgybrXE61sqKRc1QGPLtxtNpXA9B7iKOcCQQDpPh/QaQnIIMrY9zdm5YSS06e0vPd2rmlWtmX1BajDs1oSNmGy3ysfXF4rvll3IWU/hej +foMVrjpbhzlklsVXAkEAuLeIxd+6aKxauYLLb0f32IjSXEEQwTWJBo0xR2FDBxsbP900AvZi/Hln/l+0V/N018bAGSgvSb0RspDO5z2fHQJBAN6u61zlC +vAMyqWTJS2yK4N2W3bhEARII0jM5CNSKUfVP1SYlCOdPNKErac03nDrpDJXrurOae3YgwEvKzmrZ0CQHPCe0V0mhIbgRceSCvbo8xXr3Up707gQ3wiSByufYTIKyDCWxec6FRUzx4jk82cVWoT+jTK26mqJprIcrsQMiw=";

	// 支付宝公钥
	public static final String RSA_PUBLIC = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCnxj/9qwVfgoUh/y2W89L6BkRAFljhNhgPdyPuBV64bfQNN1PjbCzkIM6qRdKBoLPXmKKMiFYnkd6rAoprih3/PrQEB/VsW8OoM8fxn67UDYuyBTqA23MML9q1+ilIZwBC2AQ2UBVOrFXfFl75p6/B5KsiNG9zpgmLCUYuLkxpLQIDAQAB";

	private static final int SDK_PAY_FLAG = 1;

	private static final int SDK_CHECK_FLAG = 2;

	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case SDK_PAY_FLAG: {
				PayResult payResult = new PayResult((String) msg.obj);

				// 支付宝返回此次支付结果及加签，建议对支付宝签名信息拿签约时支付宝提供的公钥做验签
				String resultInfo = payResult.getResult();

				String resultStatus = payResult.getResultStatus();

				// 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
				if (TextUtils.equals(resultStatus, "9000")) {
					Toast.makeText(RechargeActivity.this, "支付成功",
							Toast.LENGTH_SHORT).show();
					int new_amount = Integer.parseInt(amount_back);
					tv_kubi_money.setText("酷币：" + (new_amount + old_amount));
					old_amount = new_amount + old_amount;
					et_inputmoney.setText("");

				} else {
					// 判断resultStatus 为非“9000”则代表可能支付失败
					// “8000”代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
					if (TextUtils.equals(resultStatus, "8000")) {
						Toast.makeText(RechargeActivity.this, "支付结果确认中",
								Toast.LENGTH_SHORT).show();

					} else {
						// 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
						Toast.makeText(RechargeActivity.this, "支付失败",
								Toast.LENGTH_SHORT).show();
					}
				}
				break;
			}
			case SDK_CHECK_FLAG: {
				Toast.makeText(RechargeActivity.this, "检查结果为：" + msg.obj,
						Toast.LENGTH_SHORT).show();
				break;
			}
			default:
				break;
			}
		};
	};

	/**
	 * call alipay sdk pay. 调用SDK支付
	 * 
	 */
	public void pay(String price, String order_id) {
		// 订单
		String orderInfo = getOrderInfo("酷喜乐购", "酷喜商品", price, order_id);

		// 对订单做RSA 签名
		String sign = sign(orderInfo);
		try {
			// 仅需对sign 做URL编码
			sign = URLEncoder.encode(sign, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		// 完整的符合支付宝参数规范的订单信息
		final String payInfo = orderInfo + "&sign=\"" + sign + "\"&"
				+ getSignType();

		Runnable payRunnable = new Runnable() {

			@Override
			public void run() {
				// 构造PayTask 对象
				PayTask alipay = new PayTask(RechargeActivity.this);
				// 调用支付接口，获取支付结果
				String result = alipay.pay(payInfo);
				Message msg = new Message();
				msg.what = SDK_PAY_FLAG;
				msg.obj = result;
				mHandler.sendMessage(msg);
			}
		};

		// 必须异步调用
		Thread payThread = new Thread(payRunnable);
		payThread.start();
	}

	/**
	 * check whether the device has authentication alipay account.
	 * 查询终端设备是否存在支付宝认证账户
	 * 
	 */
	public void check(View v) {
		Runnable checkRunnable = new Runnable() {

			@Override
			public void run() {
				// 构造PayTask 对象
				PayTask payTask = new PayTask(RechargeActivity.this);
				// 调用查询接口，获取查询结果
				boolean isExist = payTask.checkAccountIfExist();
				Message msg = new Message();
				msg.what = SDK_CHECK_FLAG;
				msg.obj = isExist;
				mHandler.sendMessage(msg);
			}
		};

		Thread checkThread = new Thread(checkRunnable);
		checkThread.start();

	}

	/**
	 * get the sdk version. 获取SDK版本号
	 * 
	 */
	public void getSDKVersion() {
		PayTask payTask = new PayTask(this);
		String version = payTask.getVersion();
		Toast.makeText(this, version, Toast.LENGTH_SHORT).show();
	}

	/**
	 * create the order info. 创建订单信息
	 * 
	 */
	public String getOrderInfo(String subject, String body, String price,
			String order_id) {
		// 签约合作者身份ID
		String orderInfo = "partner=" + "\"" + PARTNER + "\"";

		// 签约卖家支付宝账号
		orderInfo += "&seller_id=" + "\"" + SELLER + "\"";

		// 商户网站唯一订单号
		orderInfo += "&out_trade_no=" + "\"" + order_id + "\"";

		// 商品名称
		orderInfo += "&subject=" + "\"" + subject + "\"";

		// 商品详情
		orderInfo += "&body=" + "\"" + body + "\"";

		// 商品金额
		orderInfo += "&total_fee=" + "\"" + price + "\"";

		// 服务器异步通知页面路径
		orderInfo += "&notify_url=" + "\""
				+ "http://www.aikuxi.com/api/alipay/callback" + "\"";// homer发过来

		// 服务接口名称， 固定值
		orderInfo += "&service=\"mobile.securitypay.pay\"";

		// 支付类型， 固定值
		orderInfo += "&payment_type=\"1\"";

		// 参数编码， 固定值
		orderInfo += "&_input_charset=\"utf-8\"";

		// 设置未付款交易的超时时间
		// 默认30分钟，一旦超时，该笔交易就会自动被关闭。
		// 取值范围：1m～15d。
		// m-分钟，h-小时，d-天，1c-当天（无论交易何时创建，都在0点关闭）。
		// 该参数数值不接受小数点，如1.5h，可转换为90m。
		orderInfo += "&it_b_pay=\"30m\"";

		// extern_token为经过快登授权获取到的alipay_open_id,带上此参数用户将使用授权的账户进行支付
		// orderInfo += "&extern_token=" + "\"" + extern_token + "\"";

		// 支付宝处理完请求后，当前页面跳转到商户指定页面的路径，可空
		orderInfo += "&return_url=\"m.alipay.com\"";

		// 调用银行卡支付，需配置此参数，参与签名， 固定值 （需要签约《无线银行卡快捷支付》才能使用）
		// orderInfo += "&paymethod=\"expressGateway\"";

		return orderInfo;
	}

	/**
	 * get the out_trade_no for an order. 生成商户订单号，该值在商户端应保持唯一（可自定义格式规范）
	 * 
	 */
	public String getOutTradeNo() {
		SimpleDateFormat format = new SimpleDateFormat("MMddHHmmss",
				Locale.getDefault());
		Date date = new Date();
		String key = format.format(date);

		Random r = new Random();
		key = key + r.nextInt();
		key = key.substring(0, 15);
		return key;
	}

	/**
	 * sign the order info. 对订单信息进行签名
	 * 
	 * @param content
	 *            待签名订单信息
	 */
	public String sign(String content) {
		return SignUtils.sign(content, RSA_PRIVATE);
	}

	/**
	 * get the sign type we use. 获取签名方式
	 * 
	 */
	public String getSignType() {
		return "sign_type=\"RSA\"";
	}

}
